package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import groovy.json.JsonOutput
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_CUSTOMER_SERVICE_REPRESENTATIVE', 'ROLE_ACCOUNT_MANAGER', 'ROLE_BRANCH_GENERAL_MANAGER'])
@Transactional(readOnly = true)
class UserController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE", appLogin: "POST", appQueryUser: "POST"]

    def springSecurityService
    def passwordEncoder

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        respond User.list(params), model: [userCount: User.count()]
    }

    def show(User user)
    {
        respond user
    }

    def create()
    {
        respond new User(params)
    }

    @Transactional
    def save(User user)
    {
        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond user.errors, view: 'create'
            return
        }

        user.save flush: true

        UserRole.create(user, Role.findByAuthority('ROLE_ADMINISTRATOR'))

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect user
            }
            '*' { respond user, [status: CREATED] }
        }
    }

    def edit(User user)
    {
        def userrole = UserRole.findByUser(user)
        respond user, model: [userrole: userrole]
    }

    @Transactional
    def update(User user)
    {
        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (user.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond user.errors, view: 'edit'
            return
        }

        user.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect user
            }
            '*' { respond user, [status: OK] }
        }
    }

    @Transactional
    def delete(User user)
    {

        if (user == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        user.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), user.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label',
                                                                                          default: 'User'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['permitAll'])
    def changePassword()
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        respond user
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['permitAll'])
    @Transactional
    def updatePassword(User user)
    {
        def oldPassword = params['oldPassword']
        def newPassword = params['newPassword']

        if (passwordEncoder.isPasswordValid(user.password, oldPassword, null))
        {
            user.password = newPassword
            user.save flush: true
            render([status: "success"] as JSON)
        }
        else
        {
            flash.message = message(code: 'user.password.matches.invalid')
            // respond user, view: 'changePassword'
            render([status: "error", errorMessage: message(code: 'user.password.matches.invalid')] as JSON)
        }
    }

    /**
     * @Author 班旭娟
     * @ModifiedDate 2017-4-21
     */
    @Secured(['permitAll'])
    @Transactional
    def resetPassword()
    {
        def user = User.findById(params['user'])
        def password = params['password']
        def destination = params['destination']
        user.password = password
        if (user.validate())
        {
            user.save flush: true
            flash.message = "密码重置成功"
            if (destination)
            {
                redirect controller: destination, action: 'index'
                return
            }
            else
            {
                redirect controller: 'userTeam', action: 'index'
                return
            }
        }
        else
        {
            flash.message = user.errors
            if (destination)
            {
                redirect controller: destination, action: 'index'
                return
            }
            else
            {
                redirect controller: 'userTeam', action: 'index'
                return
            }
        }
    }

    @Secured('permitAll')
    @Transactional
    def searchUser()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0;

        def fullName = params["fullName"]
        String sql = "from User as u where 1=1"
        if (fullName)
        {
            sql += " and u.fullName like '%${fullName}%'"
        }

        sql += ' order by modifiedDate desc'

        println "sql:" + sql

        def max = params.max
        def offset = params.offset

        def list = User.findAll(sql, [max: max, offset: offset])
        def list1 = User.findAll(sql)
        def count = list1.size()

        respond list, model: [userCount: count, params: params], view: 'index'
    }

    @Secured('permitAll')
    @Transactional
    def getUserInfo()
    {
        println "************************* getUserInfo ***************************"
        render User.findByUsername("admin") as JSON
        return
    }
}
